import requests
import re
import os
import json
def get_video_url(share_url):
    headers = {
    'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/121.0.2277.107 Version/17.0 Mobile/15E148 Safari/604.1'
    }

    # 发送请求获取视频页面
    response = requests.get(share_url, headers=headers)
    video_id = response.url.split("?")[0].strip("/").split("/")[-1]
    share_url = f'https://www.iesdouyin.com/share/video/{video_id}'
    response = requests.get(share_url, headers=headers)
    response.raise_for_status()
    # 使用正则表达式提取视频信息
    pattern = re.compile(
        pattern=r"window\._ROUTER_DATA\s*=\s*(.*?)</script>",
        flags=re.DOTALL
    )
    find_res = pattern.search(response.text)
    if not find_res or not find_res.group(1):
        raise ValueError("parse video json info from html fail")
    # json_data = json.loads(find_res.group(1).strip())
    # data = json_data["loaderData"]["video_(id)/page"]["videoInfoRes"]["item_list"][0]
    try:
        json_data = json.loads(find_res.group(1).strip())
        data = (json_data.get("loaderData", {})
                .get("video_(id)/page", {})
                .get("videoInfoRes", {})
                .get("item_list", [None]))
        if not data or not data[0]:
            raise ValueError("Video data not found in JSON")
        video_data = data[0]
        video_url = video_data["video"]["play_addr"]["url_list"][0].replace("playwm", "play")
        preview_title = video_data['desc']
        preview_title = clean_string(preview_title)
        title = f"{preview_title}.mp4"
        download_video(video_url,title)
        return video_url
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON: {e}")
    except (KeyError, IndexError) as e:
        raise ValueError(f"Unexpected data structure: {e}")
    
def clean_string(text):
    # 去除所有空格
    no_space = re.sub(r'\s+', '', text)
    # 只保留中文字符、字母和数字
    cleaned = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', no_space)
    return cleaned
    
def download_video(video_url, save_path='video.mp4'):
    headers = {  
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/121.0.2277.107 Version/17.0 Mobile/15E148 Safari/604.1'
    }
    response = requests.get(video_url, headers=headers, stream=True)
    response.raise_for_status()
    with open(save_path, 'wb') as f:  
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)

if __name__ == '__main__':
    url = "https://www.douyin.com/video/7499841478136745251"
    video_url = get_video_url(url)
    print(video_url)